<?php
/**
 * 意见反馈API - 意见箱功能
 * 用户可以提交意见反馈、查看反馈状态和管理员回复
 */

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    exit;
}

// 数据库配置
$dbConfig = [
    'host' => 'localhost',
    'name' => 'nzy_congqian_cn', 
    'user' => 'nzy_congqian_cn',
    'pass' => 'FsnXrDfDhm4wFJSX',
    'charset' => 'utf8mb4'
];

// 数据库连接
try {
    $dsn = "mysql:host={$dbConfig['host']};dbname={$dbConfig['name']};charset={$dbConfig['charset']}";
    $pdo = new PDO($dsn, $dbConfig['user'], $dbConfig['pass']);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    jsonResponse([
        'success' => false,
        'message' => '数据库连接失败: ' . $e->getMessage()
    ]);
}

// 响应函数
function jsonResponse($data) {
    echo json_encode($data, JSON_UNESCAPED_UNICODE);
    exit;
}

function success($data = null, $message = '操作成功') {
    jsonResponse([
        'code' => 200,
        'success' => true,
        'message' => $message,
        'data' => $data,
        'timestamp' => time()
    ]);
}

function error($message = '操作失败', $code = 400) {
    jsonResponse([
        'code' => $code,
        'success' => false,
        'message' => $message,
        'data' => null,
        'timestamp' => time()
    ]);
}

// 验证token（兼容版本）
function verifyToken($token) {
    global $pdo;
    
    if (empty($token)) {
        return false;
    }
    
    // 移除Bearer前缀
    if (strpos($token, 'Bearer ') === 0) {
        $token = substr($token, 7);
    }
    
    try {
        // 先检查表结构
        $hasTokenField = false;
        try {
            $columns = $pdo->query("SHOW COLUMNS FROM users LIKE 'token'")->fetchAll();
            $hasTokenField = (count($columns) > 0);
        } catch (Exception $e) {
            $hasTokenField = false;
        }
        
        if ($hasTokenField) {
            // 尝试新的token验证
            $sql = "SELECT * FROM users WHERE token = ?";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$token]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($user) {
                // 检查用户状态和过期时间
                $isActive = ($user['status'] == 'active' || $user['status'] == 1);
                $isNotExpired = empty($user['token_expires']) || strtotime($user['token_expires']) > time();
                
                if ($isActive && $isNotExpired) {
                    return $user;
                }
                
                // 如果用户存在但token过期，更新过期时间并返回用户（兼容处理）
                if ($isActive) {
                    try {
                        $updateSql = "UPDATE users SET token_expires = DATE_ADD(NOW(), INTERVAL 7 DAY) WHERE id = ?";
                        $updateStmt = $pdo->prepare($updateSql);
                        $updateStmt->execute([$user['id']]);
                        return $user;
                    } catch (Exception $e) {
                        // 更新失败，继续下面的验证
                    }
                }
            }
        }
        
        // 备用方案1：尝试将token作为openid来验证
        $sql = "SELECT * FROM users WHERE openid = ?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$token]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($user) {
            $isActive = ($user['status'] == 'active' || $user['status'] == 1);
            if ($isActive) {
                return $user;
            }
        }
        
        // 备用方案2：尝试更宽松的状态检查
        $sql = "SELECT * FROM users WHERE (openid = ? OR (token IS NOT NULL AND token = ?)) AND status != 0";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$token, $token]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($user) {
            return $user;
        }
        
        return false;
        
    } catch (Exception $e) {
        // 最基础的验证
        try {
            $sql = "SELECT * FROM users WHERE openid = ? LIMIT 1";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$token]);
            return $stmt->fetch(PDO::FETCH_ASSOC);
        } catch (Exception $e2) {
            return false;
        }
    }
}

// 获取认证token
function getAuthToken() {
    $headers = getallheaders();
    $authHeader = $headers['Authorization'] ?? $headers['authorization'] ?? '';
    
    if (strpos($authHeader, 'Bearer ') === 0) {
        return substr($authHeader, 7);
    }
    
    return $_GET['token'] ?? $_POST['token'] ?? '';
}

// 获取当前用户
function getCurrentUser() {
    $token = getAuthToken();
    if (!$token) {
        error('需要登录', 401);
    }
    
    $user = verifyToken($token);
    if (!$user) {
        error('登录已过期，请重新登录', 401);
    }
    
    return $user;
}

// 提交意见反馈
function submitFeedback() {
    global $pdo;
    
    $user = getCurrentUser();
    $input = json_decode(file_get_contents('php://input'), true);
    
    // 验证必填字段
    if (empty($input['title'])) {
        error('标题不能为空');
    }
    
    if (empty($input['content'])) {
        error('反馈内容不能为空');
    }
    
    $title = trim($input['title']);
    $content = trim($input['content']);
    $feedbackType = $input['feedback_type'] ?? '一般反馈';
    $contactPhone = trim($input['contact_phone'] ?? '');
    $images = $input['images'] ?? [];
    
    // 验证标题长度
    if (mb_strlen($title) > 100) {
        error('标题长度不能超过100个字符');
    }
    
    // 验证内容长度
    if (mb_strlen($content) > 2000) {
        error('反馈内容不能超过2000个字符');
    }
    
    // 验证手机号格式（如果提供）
    if (!empty($contactPhone) && !preg_match('/^1[3-9]\d{9}$/', $contactPhone)) {
        error('手机号格式不正确');
    }
    
    // 处理图片URLs
    $imageJson = '';
    if (!empty($images) && is_array($images)) {
        // 验证图片URL格式
        foreach ($images as $image) {
            if (!filter_var($image, FILTER_VALIDATE_URL)) {
                error('图片URL格式不正确');
            }
        }
        $imageJson = json_encode($images);
    }
    
    try {
        // 创建意见反馈记录
        $insertSql = "INSERT INTO feedback 
                     (user_id, feedback_type, title, content, images, contact_phone, status, created_at, updated_at)
                     VALUES (?, ?, ?, ?, ?, ?, 0, NOW(), NOW())";
        
        $insertStmt = $pdo->prepare($insertSql);
        $insertStmt->execute([
            $user['id'],
            $feedbackType,
            $title,
            $content,
            $imageJson,
            $contactPhone
        ]);
        
        $feedbackId = $pdo->lastInsertId();
        
        success([
            'feedback_id' => $feedbackId,
            'title' => $title,
            'feedback_type' => $feedbackType,
            'status' => 'pending',
            'message' => '您的意见反馈已提交成功，我们会尽快处理'
        ], '意见反馈提交成功');
        
    } catch (Exception $e) {
        error('提交意见反馈失败: ' . $e->getMessage());
    }
}

// 获取意见反馈列表
function getFeedbackList() {
    global $pdo;
    
    $user = getCurrentUser();
    $page = max(1, intval($_GET['page'] ?? 1));
    $limit = min(50, max(1, intval($_GET['limit'] ?? 10)));
    $status = $_GET['status'] ?? '';
    $feedbackType = $_GET['feedback_type'] ?? '';
    $offset = ($page - 1) * $limit;
    
    try {
        // 构建查询条件
        $whereClause = "WHERE user_id = ?";
        $params = [$user['id']];
        
        if ($status !== '') {
            $whereClause .= " AND status = ?";
            $params[] = intval($status);
        }
        
        if ($feedbackType !== '') {
            $whereClause .= " AND feedback_type = ?";
            $params[] = $feedbackType;
        }
        
        // 查询意见反馈列表
        $sql = "SELECT * FROM feedback 
                $whereClause 
                ORDER BY created_at DESC 
                LIMIT $limit OFFSET $offset";
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        $feedbacks = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // 获取总数
        $countSql = "SELECT COUNT(*) as total FROM feedback $whereClause";
        $countStmt = $pdo->prepare($countSql);
        $countStmt->execute($params);
        $total = $countStmt->fetch(PDO::FETCH_ASSOC)['total'];
        
        // 处理数据格式
        $list = [];
        foreach ($feedbacks as $feedback) {
            $statusMap = [0 => 'pending', 1 => 'processed'];
            $images = [];
            if (!empty($feedback['images'])) {
                $images = json_decode($feedback['images'], true) ?: [];
            }
            
            $list[] = [
                'id' => intval($feedback['id']),
                'feedback_type' => $feedback['feedback_type'],
                'title' => $feedback['title'],
                'content' => $feedback['content'],
                'images' => $images,
                'contact_phone' => $feedback['contact_phone'],
                'status' => $statusMap[$feedback['status']] ?? 'unknown',
                'reply' => $feedback['reply'],
                'created_at' => $feedback['created_at'],
                'updated_at' => $feedback['updated_at']
            ];
        }
        
        success([
            'list' => $list,
            'pagination' => [
                'page' => $page,
                'limit' => $limit,
                'total' => intval($total),
                'pages' => ceil($total / $limit)
            ]
        ]);
        
    } catch (Exception $e) {
        error('获取意见反馈列表失败: ' . $e->getMessage(), 500);
    }
}

// 获取意见反馈详情
function getFeedbackDetail() {
    global $pdo;
    
    $user = getCurrentUser();
    $id = intval($_GET['id'] ?? 0);
    
    if (!$id) {
        error('反馈ID不能为空');
    }
    
    try {
        $sql = "SELECT * FROM feedback WHERE id = ? AND user_id = ?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$id, $user['id']]);
        $feedback = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$feedback) {
            error('意见反馈不存在', 404);
        }
        
        $statusMap = [0 => 'pending', 1 => 'processed'];
        $images = [];
        if (!empty($feedback['images'])) {
            $images = json_decode($feedback['images'], true) ?: [];
        }
        
        success([
            'id' => intval($feedback['id']),
            'feedback_type' => $feedback['feedback_type'],
            'title' => $feedback['title'],
            'content' => $feedback['content'],
            'images' => $images,
            'contact_phone' => $feedback['contact_phone'],
            'status' => $statusMap[$feedback['status']] ?? 'unknown',
            'reply' => $feedback['reply'],
            'created_at' => $feedback['created_at'],
            'updated_at' => $feedback['updated_at']
        ]);
        
    } catch (Exception $e) {
        error('获取意见反馈详情失败: ' . $e->getMessage(), 500);
    }
}

// 获取意见反馈统计
function getFeedbackStats() {
    global $pdo;
    
    $user = getCurrentUser();
    
    try {
        $sql = "SELECT 
                    COUNT(*) as total_feedbacks,
                    SUM(CASE WHEN status = 0 THEN 1 ELSE 0 END) as pending_count,
                    SUM(CASE WHEN status = 1 THEN 1 ELSE 0 END) as processed_count,
                    DATE(MAX(created_at)) as latest_feedback_date
                FROM feedback 
                WHERE user_id = ?";
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$user['id']]);
        $stats = $stmt->fetch(PDO::FETCH_ASSOC);
        
        // 获取反馈类型分布
        $typeSql = "SELECT feedback_type, COUNT(*) as count 
                   FROM feedback 
                   WHERE user_id = ? 
                   GROUP BY feedback_type";
        $typeStmt = $pdo->prepare($typeSql);
        $typeStmt->execute([$user['id']]);
        $types = $typeStmt->fetchAll(PDO::FETCH_ASSOC);
        
        success([
            'total_feedbacks' => intval($stats['total_feedbacks']),
            'pending_count' => intval($stats['pending_count']),
            'processed_count' => intval($stats['processed_count']),
            'latest_feedback_date' => $stats['latest_feedback_date'],
            'feedback_types' => $types
        ]);
        
    } catch (Exception $e) {
        error('获取统计信息失败: ' . $e->getMessage(), 500);
    }
}

// 获取反馈类型列表
function getFeedbackTypes() {
    try {
        // 预定义的反馈类型
        $types = [
            ['type' => '服务反馈', 'description' => '对展览服务的意见和建议'],
            ['type' => '展览反馈', 'description' => '对展览内容的意见和建议'],
            ['type' => '设施反馈', 'description' => '对博物馆设施的意见和建议'],
            ['type' => '活动反馈', 'description' => '对博物馆活动的意见和建议'],
            ['type' => '网站反馈', 'description' => '对网站功能的意见和建议'],
            ['type' => '其他反馈', 'description' => '其他意见和建议'],
            ['type' => '投诉建议', 'description' => '投诉和改进建议'],
            ['type' => '表扬感谢', 'description' => '表扬和感谢']
        ];
        
        success([
            'feedback_types' => $types
        ]);
        
    } catch (Exception $e) {
        error('获取反馈类型失败: ' . $e->getMessage(), 500);
    }
}

// 处理请求
$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';

try {
    switch ($method) {
        case 'GET':
            switch ($action) {
                case 'list':
                    getFeedbackList();
                    break;
                case 'detail':
                    getFeedbackDetail();
                    break;
                case 'stats':
                    getFeedbackStats();
                    break;
                case 'types':
                    getFeedbackTypes();
                    break;
                default:
                    error('无效的操作');
            }
            break;
            
        case 'POST':
            switch ($action) {
                case 'submit':
                    submitFeedback();
                    break;
                default:
                    error('无效的操作');
            }
            break;
            
        default:
            error('不支持的请求方法');
    }
    
} catch (PDOException $e) {
    error('数据库错误: ' . $e->getMessage(), 500);
} catch (Exception $e) {
    error('服务器错误: ' . $e->getMessage(), 500);
}
?>